<template>
  <div class="app-container">
    <el-row type="flex" align="middle">
      <el-col>
        <div style="display: flex; align-items: center;" class="dropdown">
          <span class="frequency">刷新频率:</span>
          <el-dropdown size="small" split-button type="primary" class="dropdown" @command="handleCommand">
            {{ selectedTime }}
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="time in timeOptions" :key="time" :command="time">{{ time }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-col>
    </el-row>
    <el-collapse v-model="activeName" style="margin-top: 20px;">
      <el-collapse-item
        v-for="(line, lineIndex) in znddDeviceList"
        :key="lineIndex"
        :title="`${znddLineTypeFormatter(line.lineType)} - ${line.threeLineName}`"
        :name="`${line.lineType}-${line.threeLineName}`"> <!-- 使用 lineType 和 threeLineName 的组合作为 name -->
        <el-row :gutter="20">
          <el-col :lg="{span:4}" :offset="0" :span="4" v-for="(device, deviceIndex) in line.znddLineInfoVOS" :key="deviceIndex"
          style="display: flex;justify-content: center;align-items: center;box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5);transition: color 0.3s;background-color: #f5f5f5;margin-left: 1.5rem;">
            <el-card :body-style="{ padding: '0px' }">
              <img src='@/images/robotImg.png' class="imageOfStatus">
              <div style="padding: 14px;" class="cardInfo clearfix">
                <span>名称：{{ device.deviceName }}</span><br>
                <div class="statusInfo">
                  <div class="status-before">
                    状态：
                  </div>
                  <div style="padding: 0.3rem;">
                  <el-tag type="warning" effect="dark" v-if="device.deviceStatus == 1">{{ znddDeviceStatusFormatter(device.deviceStatus) }}</el-tag>
                  <el-tag type="success" effect="dark" v-if="device.deviceStatus == 2">{{ znddDeviceStatusFormatter(device.deviceStatus) }}</el-tag>
                  <el-tag type="danger" effect="dark" v-if="device.deviceStatus == 3">{{ znddDeviceStatusFormatter(device.deviceStatus) }}</el-tag>
                  </div>
                  <!-- <div
                    class="status-after"
                    :style="{ backgroundColor: statusColor(device.deviceStatus), color: fontColor(device.deviceStatus)}"
                  >
                    {{ znddDeviceStatusFormatter(device.deviceStatus) }}
                  </div> -->
                </div>
                <div class="bottom">
                  <el-button type="primary" class="button" @click="openDialog(device)" size="mini">状态修改</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-collapse-item>
    </el-collapse>


    <!-- 修改设备状态框 -->
    <el-dialog style="align-content: center;" :title="title" :visible.sync="open" width="380px" append-to-body>
      <el-form ref="form" align="center" :model="form"   label-width="80px">
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-select v-model="form.deviceStatus" placeholder="请选择设备状态">
            <el-option
              v-for="dict in znddDeviceStatusS"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectDeviceList ,edit } from "@/api/zndd/intelligence/deviceStatus";
import { getDeviceStatus } from "@/api/zndd/device/device";

export default {
  name: "deviceStatus",
  data() {
    return {
      selectedTime: '5秒钟',
      allTimes: ['5秒钟', '10秒钟', '20秒钟', '30秒钟', '40秒钟', '50秒钟'],
      // 产线列表
      znddDeviceList: [],
      // 设备状态字典
      znddDeviceStatusS: [],
      // 产线类型字典
      znddLineTypeS: [],
      //默认列表
      activeName: [], // 存储展开的折叠项
      expandedItems: {}, // 存储每个折叠项的展开状态
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
    };
  },
  computed: {
    timeOptions() {
      return this.allTimes.filter(time => time !== this.selectedTime);
    },
    timeInMilliseconds() {
      const seconds = parseInt(this.selectedTime.replace('秒钟', ''), 10);
      return seconds * 1000;
    },
    statusColor() {
      return (status) => {
        switch (status) {
          case '1':
            return '#4CAF50'; // 绿色
          case '3':
            return '#FFC107'; // 黄色
          case '2':
            return '#F44336'; // 红色
          default:
            return '#0a3259'; // 默认颜色
        }
      };
    },
    fontColor() {
      return (status) => {
        switch (status) {
          case '1':
            return '#fffefd'; // 绿色
          case '3':
            return '#fffefd'; // 黄色
          case '2':
            return '#fffefd'; // 红色
          default:
            return '#0a0b0b'; // 默认颜色
        }
      }
    },
  },
  created() {
    // 获取报工信息
    this.getList();
    // 获取字典表中设备类型
    this.getDicts("zndd_device_status").then(response => {
      this.znddDeviceStatusS = response.data;
    });
    // 获取字典表中产线类型
    this.getDicts("zndd_line_type").then(response => {
      this.znddLineTypeS = response.data;
    });
    // 初始化定时器
    this.startTimer();
    // 初始化 expandedItems
    if (this.znddDeviceList.length > 0) {
      this.expandedItems[`${this.znddDeviceList[0].lineType}-${this.znddDeviceList[0].threeLineName}`] = true;
    }
  },
  beforeDestroy() {
    // 清除定时器
    this.clearTimer();
  },
  watch: {
    selectedTime() {
      // 当 selectedTime 改变时，重新设置定时器
      this.resetTimer();
    },
    activeName(newVal) {
      this.expandedItems = {};
      newVal.forEach(name => {
        this.expandedItems[name] = true;
      });
    }
  },
  methods: {
    //格式化设备类型
    znddDeviceStatusFormatter(info){
      const znddDeviceStatus = this.znddDeviceStatusS.find(znddDeviceStatus => znddDeviceStatus.dictValue === info);
      return znddDeviceStatus ? znddDeviceStatus.dictLabel : '';
    },
    //格式化产线类型
    znddLineTypeFormatter(info){
      const znddLineType = this.znddLineTypeS.find(znddLineType => znddLineType.dictValue === info);
      return znddLineType ? znddLineType.dictLabel : '';
    },
    //查询设备列表方法
    getList() {
      selectDeviceList().then(response => {
        this.znddDeviceList = response;
        if (this.znddDeviceList.length > 0) {
          // 根据 expandedItems 更新 activeName
          this.activeName = this.znddDeviceList
            .map(line => `${line.lineType}-${line.threeLineName}`)
            .filter(name => this.expandedItems[name]);

          // 如果没有展开的项，则默认展开第一个
          if (this.activeName.length === 0 && this.znddDeviceList.length > 0) {
            this.activeName = [`${this.znddDeviceList[0].lineType}-${this.znddDeviceList[0].threeLineName}`];
            this.expandedItems[this.activeName[0]] = true;
          }
        }
      });
    },
    handleCommand(command) {
      this.selectedTime = command;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        deviceNo: null,
        deviceName: null,
        deviceModel: null,
        deviceSpecification: null,
        deviceStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form)
          edit(this.form).then(response => {
            console.log(response)
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    // 打开状态修改对话框
    openDialog(device) {
      this.reset();
      const id = device.id
      getDeviceStatus(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工单状态";
      });
    },
    //定时器相关
    startTimer() {
      this.timer = setInterval(() => {
        this.getList();
      }, this.timeInMilliseconds);
    },
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    resetTimer() {
      this.clearTimer();
      this.startTimer();
    },
  }
};
</script>
<style>
.dropdown{
  float: right;
}
.imageOfStatus {
  width: 100%;
  height: 90%;
  display: block;
  background-size: cover;
}

.clearfix:before,
.clearfix:after {
  content: '';
  display: table;
  clear: both;
}

.clearfix:after {
  clear: both
}
.bottom{
  display:flex;justify-content: center;align-items: center;
}
.el-card {
  margin-top: 5px;
  margin-bottom: 5px;
  margin-left: 15px;
  margin-right: 15px;
  /*  border: 2px solid #409EFF;*/ /* 更美观的边框实线，颜色为蓝色 */
  border-radius: 8px; /* 圆角边框 */
  box-shadow: 0 2px 12px 0 rgb(204, 217, 228); /* 添加阴影效果 */
}
.el-card-info{
  margin-left: 15px;
}
.cardInfo{
  background-color: #ccd9e4;
}
span {
  font-size: 14px;
}
.frequency{
  margin-right: 15px;
}
.statusInfo{
  height: 50px;
  display: flex;
}
.status-before{
  margin-top: 10px;
}
.status-after{
  margin-top: 5px;
  width: 60px;
  height: 30px;
  text-align: center;
  font-size: 15px;
  color: #fffefd;
  line-height: 30px;
}
</style>
